package com.itbupt.eat.filter;

import com.itbupt.eat.common.BaseContext;
import com.itbupt.eat.entity.Employee;
import com.alibaba.fastjson.JSON;
import com.itbupt.eat.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.LogRecord;


/**
 * @Author BUPT-Dingchang
 * @Create 2024/4/20 22:27
 * ClassName: LoginCheckFilter
 * Description:
 */

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    // Spring框架提供的路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

         // 强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1. 获取本次请求的url
        String requestURI = request.getRequestURI();

        // 2. 定义不需要拦截的url地址数组
        String[] urls = new String[] {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "front/**",
        };

        // 3. 判断本次请求的url是否需要拦截
        Boolean check = check(urls, requestURI);

        // 4.如果check为true则不需要处理，直接放行
        if(check) {
            filterChain.doFilter(request, response);
            return;
        }

        // 5.如果需要处理，则判断登录状态
        if(request.getSession().getAttribute("employee") != null) {
            // 能进入说明已经登录，直接放行

            Long id = (Long) request.getSession().getAttribute("employee");
            log.info("用户{}已登录", id);

            // 把当前登录用户的ID保存到ThreadLocal中
            BaseContext.setCurrentUserId(id);

            filterChain.doFilter(request, response);
            return;
        }

        // 6.走到这里就是没登录
        // 向浏览器响应一个流，让前端读到R里面的数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));


        // 打印日志
        log.info("拦截到请求：{}", request.getRequestURI());
        // 放行
        filterChain.doFilter(request, response);
    }

    // 核查请求URL是否在放行URL数组中，检查本次请求是否需要放行
    private Boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        // 循环完了都匹配不上就返回false
        return false;
    }
    
}
